<template>
	<view class="address-form">
		<gyd-navbar back-color="#fff" :title="title"></gyd-navbar>

		<view class="form">
			<view class="form-item">
				<text class="label">收货人</text>
				<view class="form-input">
					<input v-model="formData.consignee" type="text" placeholder="请填写您的姓名" />
				</view>
			</view>

			<view class="form-item">
				<text class="label">手机号</text>
				<view class="form-input">
					<input v-model="formData.mobile" type="number" placeholder="请填写您的手机号" />
				</view>
			</view>

			<!-- #ifdef H5 -->
			<view class="form-item">
				<text class="label">所在地区</text>
				<view class="form-input">
					<uni-data-picker v-model="formData.area" :localdata="areaList" popup-title="请选择收货地区"
						@change="areaConfirm"></uni-data-picker>
				</view>
			</view>
			<!-- #endif -->
			<!-- #ifdef MP || APP -->
			<view class="form-item" @click="chooseLocation">
				<text class="label">所在地区</text>
				<view class="form-input">
					<input type="text" v-model="formData.select_address" placeholder="请选择所在地区" />
				</view>
				<u-icon name="arrow-right"></u-icon>
			</view>
			<!-- #endif -->
			<view class="form-item">
				<text class="label">详细地址</text>
				<view class="form-input">
					<textarea v-model="formData.address" placeholder="请填写详细地址" />
				</view>
			</view>

			<!-- <view class="form-item">
				<text class="label">标签</text>
				<view class="tags">
					<text :class="seledtedTag==item.value?'checked':''" v-for="(item, index) in addressTags"
						:key="index" @click="changeTags(item)">{{item.name}}</text>
					<text @click="showAddTags">+</text>
				</view>
			</view> -->

			<u-cell style="padding-left: 0; padding-right: 0;" title="设置默认地址"
				:title-style="{fontSize: '28rpx', fontWeight: 'bold'}" label="每次下单会默认推荐该地址"
				:label-style="{fontSize: '24rpx', margin: 0, fontWeight: 'normal'}">
				<template #value>
					<u-switch v-model="formData.is_default" @change="changeDefault()"></u-switch>
				</template>
			</u-cell>

			<u-button class="btn" shape="circle" @click="submit()">立即提交</u-button>
		</view>

		<u-popup :show="showTagsRef" class="tags-popup" :round="10" mode="center" :closeable="true"
			@close="closeAddTags()">
			<view class="tags-content">
				<view class="content">
					<input v-model="tagName" type="text" placeholder="请填写标签" />
				</view>
				<view class="btn-group">
					<u-button type="warning" size="mini" @click="closeAddTags">取消</u-button>
					<u-button type="primary" size="mini" @click="saveTags">提交</u-button>
				</view>
			</view>
		</u-popup>
	</view>
</template>

<script setup>
	import request from '@/utils/request';
	import cache from '@/utils/cache';
	import util from '@/utils/util';
	import {
		ref,
		reactive,
		toRefs,
		inject,
	} from 'vue';
	import {
		onLoad,
		onShow,
		onReady,
		onPullDownRefresh,
		onReachBottom,
	} from '@dcloudio/uni-app';

	const state = reactive({
		title: '地址创建',
		themeColor: cache.get('themeColor'),
		imgHost: util.requestUrl(),
		show_city: false,
		address: [],
		formData: {
			consignee: "",
			mobile: "",
			province: 0,
			city: 0,
			area: 0,
			town: 0,
			areaCode: '',
			longitude: '',
			latitude: '',
			tags: 0,
			is_default: false,
			select_address: "点击选择您的地址", // 地区
			address: "", // 详细地址
			falg: 'user',
		},
		is_h5: false,
		seledtedTag: 0,
		addressTags: [{
			name: '家',
			value: 1,
		}, {
			name: '公司',
			value: 2,
		}, {
			name: '学校',
			value: 3,
		}],
		areaList: [], // 地区列表
		tagName: '',
		location: {
			province: '定位中...',
			city: '定位中...',
			area: '定位中...',
			town: '定位中...',
			street: '定位中...',
			address: '',
			areaCode: '',
		}, // 定位信息
	});

	// 创建响应式数据
	const showTagsRef = ref(false);

	//在页面所有元素加载完成后执行（只执行一次）
	onLoad((opt) => {
		console.log('onLoad');
		if (opt.hasOwnProperty('id')) {
			console.log('传递参数', opt.id);
			state.title = '地址编辑';
			getAddress(opt.id);
		}
		initData();
	});

	//在页面由不可见变为可见时执行（只要页面显示都会执行）
	onShow(() => {
		console.log('onShow');
	})

	//在页面解析完成之后执行
	onReady(() => {
		console.log('onReady');
	})

	onPullDownRefresh(() => {
		console.log('下拉刷新');
		setTimeout(() => {
			uni.stopPullDownRefresh();
		}, 1000);
	})

	onReachBottom(() => {
		console.log('触底加载更多');
	})

	const getAddress = (id) => {
		request.get('address/detail', {
			id: id
		}).then(res => {
			console.log('地址详情', res);
			state.formData = res.data;
		})
	}

	function initData() {
		getCity();
		// #ifdef H5
		state.is_h5 = true;
		// #endif
		// #ifdef MP || APP
		state.is_h5 = false;
		// #endif
	}

	// 获取省市区县编码
	function getCity() {
		let city = cache.get("shop_getCity");
		if (city) {
			state.areaList = city;
			return;
		}

		request.get("address/getThreeArea", {})
			.then(res => {
				state.areaList = res.data;
				cache.set('shop_getCity', res.data);
			})
			.catch(err => {
				console.log('获取数据异常', err);
			})
	}

	// 确认选择地区
	function areaConfirm(res) {
		console.log('确认选择地区', res);
		const data = res.detail.value;
		let areaStr = data[0].text + data[1].text + data[2].text;
		state.formData.select_address = areaStr;
		// 省，市，县编码
		state.formData.province = data[0].value;
		state.formData.city = data[1].value;
		state.formData.area = data[2].value;
		console.log('areaConfirm', state.formData);
	}

	// 地图选点
	const chooseLocation = () => {
		return new Promise(resolve => {
			uni.chooseLocation({
				success: (e) => {
					resolve(e);
					console.log('成功', e);
					state.formData.select_address = e.address;
					state.formData.address = e.name;
					state.formData.longitude = e.longitude;
					state.formData.latitude = e.latitude;
					getPosition();
				},
				fail: (err) => {
					console.log('获取定位失败、用户取消', err)
				}
			})
		})
	}

	const getPosition = () => {
		request.get('amap/regeo', {
			longitude: state.formData.longitude || '',
			latitude: state.formData.latitude || '',
		}).then(res => {
			console.log('地址逆解析', res);
			state.location = res.data;
			state.formData.select_address = res.data.province + res.data.city + res.data.area;
			let areaCode = state.location.areaCode;
			state.formData.areaCode = areaCode;
			if (areaCode.length >= 9) {
				state.formData.province = areaCode.substr(0, 2);
				state.formData.city = areaCode.substr(0, 4);
				state.formData.area = areaCode.substr(0, 6);
				state.formData.town = areaCode.substr(0, 9);
			}
			console.log('地址逆解析', state.location, state.formData);
		});
	}

	const onChange = (e) => {
		console.log('选中地址', e);
	}

	const changeTags = (item) => {
		console.log('选择标签', item);
		state.seledtedTag = item.value;
		state.formData.tags = item.value;
	}

	const showAddTags = () => {
		console.log('打开添加标签');
		showTagsRef.value = true;
	}

	const closeAddTags = () => {
		showTagsRef.value = false;
	}

	const saveTags = () => {
		if (!util.username(state.tagName, '标签名')) {
			return;
		}
		console.log('保存标签', state.tagName);
		let len = state.addressTags.length;
		state.addressTags.push({
			name: state.tagName,
			value: len + 1,
		})
		closeAddTags();
	}

	const changeDefault = () => {
		console.log('默认地址', state.formData.is_default);
	}

	const submit = () => {
		if (verifyForm()) {
			state.formData.is_h5 = state.is_h5;
			console.log('提交表单', state.formData);
			request.post('address/save', state.formData).then(res => {
				console.log('保存收货地址', res);
				util.showTip(res.msg);
				if (res.code == 1) {
					uni.$emit('refresh', true);
					setTimeout(() => {
						uni.navigateBack({
							delta: 1
						})
					}, 1000);
				}
			})
		}
	}

	const verifyForm = () => {
		if (!util.username(state.formData.consignee, '收货人姓名')) {
			return false;
		}
		if (!util.mobile(state.formData.mobile, '收货人电话')) {
			return false;
		}
		if (!state.formData.province || !state.formData.city || !state.formData.area) {
			util.showTip('请选择地区');
			return false;
		}
		if (!util.username(state.formData.address, '详细收货地址')) {
			return false;
		}
		return true;
	}

	function pageRoute(url) {
		uni.navigateTo({
			url
		});
	}

	function pageTabRoute(url) {
		uni.reLaunch({
			url
		});
	}

	const {
		title,
		themeColor,
		imgHost,
		show_city,
		address,
		formData,
		is_h5,
		seledtedTag,
		addressTags,
		areaList,
		tagName,
		location,
	} = toRefs(state);
</script>

<style lang="scss">
	page {
		background-color: $u-bg-reverse-color;
	}

	.address-form {
		.form {
			padding: $m20;

			.form-item {
				@include f-between;
				padding: $m32 0;
				border-bottom: 1px solid $u-border-color;

				&:last-child {
					border-bottom: none;
				}

				.label {
					width: 160rpx;
					font-weight: bold;
					color: $u-main-color;
				}

				.form-input {
					@include f-between;
					flex: 1;

					textarea {
						flex: 1;
						width: 100%;
						height: 120rpx;
						padding: $m12;
						background-color: $u-bg-color;
						border-radius: $radius-12;
					}

					input {
						flex: 1;
						color: $u-content-color;
					}
				}

				.tags {
					flex: 1;
					display: flex;
					flex-wrap: wrap;
					align-items: center;

					text {
						margin: $m12;
						padding: 0.2em 1.2em;
						font-size: $font-24;
						border-radius: $radius-100;
						border: 1px solid $u-border-color;

						&.checked {
							background-color: #2979ff;
							color: $u-reverse-color;
							border-color: #2979ff;
						}
					}
				}
			}

			.btn {
				width: 100%;
				height: 80rpx;
				line-height: 80rpx;
				border-radius: 40rpx;
				background: linear-gradient(to right, #125cd7, #279dfa);
				color: #fff;
				text-align: center;
			}
		}

		.tags-popup {
			width: 90%;

			.tags-content {
				height: 200rpx;

				.content {
					margin-top: 50rpx;
				}

				.btn-group {
					margin-bottom: 20px;
					display: flex;
				}
			}
		}
	}
</style>